package org.sikyon.chocolatebiscuit.model;

import org.sikyon.chocolatebiscuit.model.exceptions.MoneyFormatException;

import javax.annotation.concurrent.Immutable;
import java.math.BigDecimal;
import java.math.RoundingMode;

@Immutable
public final class Money {

    /**
     * The regular expression to which Strings representing Money must abide.
     */
    public static final String REGEX = "\\$?[0-9]+\\.[0-9]*";

    private final BigDecimal amount;

    private Money(BigDecimal amount) {
        this.amount = amount;
    }

    public String toString() {
        return String.format("$%s", amount.toString());
    }

    public static Money parse(String m) {
        if (!m.matches(REGEX)) {
            throw new MoneyFormatException(m);
        }
        if (m.charAt(0) == '$') {
            m = m.substring(1);
        }
        return new Money(new BigDecimal(m).setScale(2, RoundingMode.DOWN));
    }

    // TODO code equals & hashCode methods
}
